<?php
declare (strict_types=1);

namespace app\common\util;

use Firebase\JWT\JWT;

/**
 * JWT加密解密
 * Class JwtUtil
 * @package app\util
 */
class JwtUtil
{
    /**
     * jwt加密
     * @param $payload object|array
     * @return 加密后的字符串
     */
    public static function encode($payload)
    {
        $key = config('system.jwt_secret_key');
        $algorithm = config('system.jwt_algorithm');
        if (!$key || !$algorithm) {
            throw new \app\MyException(10003);
        }
        return JWT::encode($payload, $key, $algorithm);
    }

    /**
     * jwt解密
     * @param $payload object|array
     * @return 加密后的字符串
     */
    public static function decode($jwt)
    {
        $key = config('system.jwt_secret_key');
        $algorithm = config('system.jwt_algorithm');
        if (!$key || !$algorithm) {
            throw new \app\MyException(10003);
        }
        try {
            $decode = JWT::decode($jwt, $key, array($algorithm));
            return $decode;
        } catch (\app\MyException $e){
            return false;
        }
    }
}